package com.hjm.friend.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hjm.common.core.constants.Constants;
import com.hjm.common.core.domain.page.PageDomain;
import com.hjm.common.core.domain.page.TableDataInfo;
import com.hjm.common.core.utils.ThreadLocalUtils;
import com.hjm.friend.domain.message.Message;
import com.hjm.friend.domain.message.vo.MessageTextCacheVO;
import com.hjm.friend.manage.MessageCacheManager;
import com.hjm.friend.mapper.message.MessageMapper;
import com.hjm.friend.mapper.message.MessageTextMapper;
import com.hjm.friend.service.user.IUserMessageService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    MessageCacheManager messageCacheManager;

    @Autowired
    MessageTextMapper messageTextMapper;

    @Autowired
    MessageMapper messageMapper;




    @Override
    public TableDataInfo selectUserMessageList(PageDomain pageDto) {
        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);

        // 从redis 中 获取数据
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextCacheVO> messageTextVOList =new ArrayList<>();


        if(total == null || total <= 0 ){
            // 从数据库中获取数据
            PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);

            messageCacheManager.refreshCache(userId);
            total = new PageInfo(messageTextVOList).getTotal();
        }else messageTextVOList = messageCacheManager.getMsgTextVOList(pageDto, userId);

        if(Collections.isEmpty(messageTextVOList)){
            return TableDataInfo.empty();
        }

        return TableDataInfo.success(messageTextVOList,total);
    }

    @Override
    public boolean delete(Long textId) {
        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        // 删除缓存
        messageCacheManager.deleteCache(userId, textId);

        // 删除数据库
        messageTextMapper.deleteById(textId);
        messageMapper.selectOne(new LambdaQueryWrapper<Message>().eq(Message::getTextId, textId)
                .eq(Message::getRecId, userId));

        return true;
    }
}
